function msgFn(deviceid, imgSource, width, height) {
  return JSON.stringify({
    func: "showImageOnDevices",
    param0: deviceid,
    param1: imgSource,
    param2: width,
    param3: height,
  });
}

let deviceList = [
  {
    id: "3800756696423979041",
    name: "新西线16903开关",
    gh: "100kW",
    rl: "4000kWh",
  },
  {
    id: "3800756696423979049",
    name: "新西线16903开关",
    gh: "1000kW",
    rl: "2000kWh",
  },
  {
    id: "3800756696423979182",
    name: "新西线16903开关",
    gh: "500kW",
    rl: "1000kWh",
  },
];

import { Message } from "element-ui";
import { queryPlansData } from "@/api/common.js";
import { selectEnergyStoragePlanScheme, CLlist, JDlist } from "@/api/second.js";
import { queryTableList } from "@/api/UsageAnalysis.js";

export default {
  name: "maintenanceRecord",
  data() {
    return {
      selectEnergyStoragePlanScheme,
      CLlist,
      JDlist,
      formData: new FormData(),
      excelData: [],
      columns: [],
      getFrom: {}, //每行的数据
      dispatchList: [], //调度
      stationTypeLists: [], //类型
      adjustRegulationLists: [], //上下调投入分类下拉框的数据
      voltageLevelLists: [], //电压等级下拉框的数据
      addDialogVisibleTitle: "新增",
      id: 0,
      dataTree: [],
      currentLivingId: "",
      isYes: [
        {
          label: "是",
          value: 1,
        },
        {
          label: "否",
          value: 0,
        },
      ],

      defaultProps: {
        children: "list",
        label: "name",
      },
      queryDetailParam: {
        regulationOrgIds: [],
        stationIds: [],
        fileSort: "01",
        testDate: "",
        testNumber: "",
        isAudited: 1,
      },
      queryDetailParam2: {
        planId: "",
        feederStatusType: "",
        fileSort: "01",
        page: {
          pageIndex: 1,
          pageSize: 10,
        },
      },
      queryData: {
        planId: "1",
        feederStatusType: 1,
        page: {
          pageIndex: 1,
          pageSize: 10,
        },
      },
      operate: "add",
      testNumberList: [], //测试序号
      isYes: [
        {
          label: "是",
          value: 1,
        },
        {
          label: "否",
          value: 0,
        },
      ],
      secondHeards: [
        {
          name: "规划前",
          value: "type1",
        },
        {
          name: "规划后",
          value: "type2",
        },
      ],
      headList2: [
        {
          name: "规划节点",
          value: "nodeId",
          noSort: true,
          inSecond: false,
        },
        {
          name: "储能规划功率（kW）",
          value: "ratedP",
          noSort: true,
          inSecond: false,
        },
      ],
      headList: [
        {
          name: "电源节点编号",
          value: "nodeId",
          noSort: true,
          inSecond: false,
        },
        {
          name: "有功功率(kW)",
          value: "preActivePower",
          noSort: true,
          inSecond: true,
          type: "type1",
        },
        {
          name: "无功功率(kvar)",
          value: "preReactivePower",
          noSort: true,
          inSecond: true,
          type: "type1",
        },
        {
          name: "A相电压（kV）",
          value: "preVoltageAB",
          noSort: true,
          inSecond: true,
          type: "type1",
        },
        {
          name: "B相电压（kV）",
          value: "preVoltageBC",
          noSort: true,
          inSecond: true,
          type: "type1",
        },
        {
          name: "C相电压（kV）",
          value: "preVoltageAC",
          noSort: true,
          inSecond: true,
          type: "type1",
        },
        {
          name: "A相电流（A）",
          value: "preCurrentA",
          noSort: true,
          inSecond: true,
          type: "type1",
        },
        {
          name: "B相电流（A）",
          value: "preCurrentB",
          noSort: true,
          inSecond: true,
          type: "type1",
        },
        {
          name: "C相电流（A）",
          value: "preCurrentC",
          noSort: true,
          inSecond: true,
          type: "type1",
        },

        {
          name: "有功功率(kW)",
          value: "sufActivePower",
          noSort: true,
          inSecond: true,
          type: "type2",
        },
        {
          name: "无功功率(kvar)",
          value: "sufReactivePower",
          noSort: true,
          inSecond: true,
          type: "type2",
        },
        {
          name: "A相电压（kV）",
          value: "sufVoltageAB",
          noSort: true,
          inSecond: true,
          type: "type2",
        },
        {
          name: "B相电压（kV）",
          value: "sufVoltageBC",
          noSort: true,
          inSecond: true,
          type: "type2",
        },
        {
          name: "C相电压（kV）",
          value: "sufVoltageAC",
          noSort: true,
          inSecond: true,
          type: "type2",
        },
        {
          name: "A相电流（A）",
          value: "sufCurrentA",
          noSort: true,
          inSecond: true,
          type: "type2",
        },
        {
          name: "B相电流（A）",
          value: "sufCurrentB",
          noSort: true,
          inSecond: true,
          type: "type2",
        },
        {
          name: "C相电流（A）",
          value: "sufCurrentC",
          noSort: true,
          inSecond: true,
          type: "type2",
        },
      ],
      // 新增弹框显示
      dialogFormVisible: false,
      formLabelWidth: "80px",
      // 预览弹框f
      dialogPreVisible: false,
      paramData: [],
      checkList: [],
      checkId: "",
      queryParamStationId: "",
      showXLSX: false,
      xData: [
        "4.1",
        "4.2",
        "4.3",
        "4.4",
        "4.5",
        "4.6",
        "4.7",
        "4.8",
        "4.9",
        "4.10",
        "4.11",
        "4.12",
      ],
      dxtUrl: "",
      planName: "",
      energyPlanTarget: "",
      pconstraint: "",
      energyConstraint: "",
      feederId: "",
      countConstraint: "",
      // 变电站下拉列表 "",
      stationOptions: [
        {
          value: "001",
          label: "变电站1",
        },
        {
          value: "002",
          label: "变电站2",
        },
      ],
      // 馈线下拉列表
      lineOptions: [
        {
          value: "001",
          label: "变电站1",
        },
        {
          value: "002",
          label: "变电站2",
        },
      ],
      upForm: {
        // 缓存状态类型
        statusType: "",
      },

      // 缓存状态类型列表
      statusTypeOptions: [
        {
          value: 1,
          label: "倒送状态",
        },
        {
          value: 2,
          label: "高负载状态",
        },
        {
          value: 3,
          label: "冬季典型状态",
        },
        {
          value: 4,
          label: "夏季典型状态",
        },
        {
          value: 5,
          label: "春秋典型状态",
        },
      ],
      bottomForm: {
        // 变电站id
        date: this.dateFormat(new Date().getTime()),
      },
      value: 1,
      options: [
        {
          value: 1,
          label: "倒送状态",
        },
        {
          value: 2,
          label: "高负载状态",
        },
        {
          value: 3,
          label: "冬季典型状态",
        },
        {
          value: 4,
          label: "夏季典型状态",
        },
        {
          value: 5,
          label: "春秋典型状态",
        },
      ],
      dialogVisible: false,
      percentage: 20,
      filterText: "",
      currentPlanId: "",
      // 树节点相关
      allIds: [],
      defaultExpandedNode: [],
      currentKey: "",

      isBubble: false,
    };
  },

  mounted() {
    // this.dxtInit();
    this.getTreeData();

    window.addEventListener("message", function (e) {
      let data = JSON.parse(e.data);
      if (data.fun == "graphLoadFinish") {
        document
          .getElementById("iframe")
          .contentWindow.postMessage(
            msgFn(
              [
                "3800756610524633262",
                "3800756610524633121",
                "3800756610524633129",
              ],
              "energyStorageBlack.png",
              40,
              40
            ),
            "*"
          );
      }
      if (data.fun == "clickDeviceImage") {
        this.isBubble = !this.isBubble;
        let param = "";
        if (this.isBubble) {
          let showObj = deviceList.filter((item) => item.id == data.param0);
          param = `;isReload=1;graph=%E6%96%B0%E8%A5%BF169%E7%BA%BF%E5%8D%95%E7%BA%BF%E5%9B%BE.sln.pic.g;facBubble=${data.param0}_align=0^fs=16^alignSec1=0^alignSec2=0^ts=节点名称：${showObj[0].name}@n储能规划：${showObj[0].gh}@n储能容量：${showObj[0].rl}`;
        } else {
          param = `;isReload=1;graph=%E6%96%B0%E8%A5%BF169%E7%BA%BF%E5%8D%95%E7%BA%BF%E5%9B%BE.sln.pic.g;`;
        }
        let msg = JSON.stringify({ func: "urlUtilGraph", param0: param });
        setTimeout(() => {
          document.getElementById("iframe").contentWindow.postMessage(msg, "*");
        }, 1000);
      }
    });
  },
  created() {
    // this.regulationOrgList()
    // this.stationTypeList()
    // this.adjustRegulationList()
    // this.voltageLevelList()
    // this.getTreeData()
    // this.queryStationTestNumber()
    this.initIframeFn();
  },

  watch: {
    filterText(val) {
      this.$refs.equipmentTree.filter(val);
    },
    // $route: {
    //   handler(to, from) {
    //     console.log("from: ", from);
    //     console.log("to: ", to);
    //     if (to.query.activeName == "queryYxdnb") {
    //       this.activeName = "queryYxdnb";
    //     }
    //   },
    //   deep: true, // 深度监听
    //   immediate: true, // 第一次初始化渲染就可以监听到
    // },
  },

  methods: {
    handleCheck(data) {
      if (data.id) {
        this.queryData.planId = data.id;
        this.querygre();
        this.$refs.windPowerTable.getDataInit();
        this.$refs.windPowerTable2.getDataInit();
      }
    },
    customColorMethod(percentage) {
      if (percentage < 30) {
        return "#909399";
      } else if (percentage < 70) {
        return "#e6a23c";
      } else {
        return "#67c23a";
      }
    },

    open() {
      let timer = setTimeout(() => {
        //需要定时执行的代码
        this.increase();
        if ((this.percentage = 100)) {
          clearTimeout(timer);
        }
      }, 5000);
    },
    increase() {
      this.percentage += 10;
      if (this.percentage > 100) {
        this.percentage = 100;
      }
    },

    settings() {
      this.dialogVisible = true;
    },

    cancel() {
      this.dialogVisible = false;
      this.percentage = 20;
      this.$router.push({ name: "cnrlAnalysis" });
    },

    dateFormat(val) {
      let date = new Date(val);
      let year = date.getFullYear();
      let month =
        date.getMonth() + 1 > 9
          ? date.getMonth() + 1
          : "0" + (date.getMonth() + 1);
      let day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();

      return year + "-" + month + "-" + day;
    },
    // dxtInit(){
    // 	let gzqytmp='keyidrect=FFCC33_';
    // 	if(this.gzqyid)gzqytmp+=this.gzqyid;
    // 	let faultdescId = this.deviceIdlist.join(':');
    // 	gzqytmp += ';faultdesc=' + faultdescId;
    // 	let bigStr = 'graph=' + this.rowParamsObj.dxt + ';isClient=1;menubarshow=0;appmode=3;isFault=1;100p;100p;isgray=0;' + gzqytmp;
    // 	console.log(bigStr);
    // 	let msg = JSON.stringify({
    // 		fun: 'urlUtilGraph',
    // 		param0: bigStr,
    // 	});
    // 	setTimeout(() => {
    // 		this.$refs.dxt.contentWindow.postMessage(msg, '*');
    // 	}, 2000)
    // },

    async getTreeData() {
      let { resultCode, data } = await queryPlansData(this.queryDetailParam);
      if (resultCode == 0) {
        this.dataTree = data;
        this.dataTreeFn(data);
        this.currentKey = this.allIds[0];

        if (this.currentKey) {
          // 默认展开第一条
          this.defaultExpandedNode.push(this.currentKey);
          this.queryDetailParam.planId = this.currentKey;
          this.expandDefault();
          this.handleCheck({ id: this.currentKey });
        }
      }
    },

    // 默认展开第一条
    expandDefault() {
      if (this.currentKey) {
        this.$nextTick(() => {
          this.$refs.equipmentTree.setCurrentKey(this.currentKey);
        });
      }
    },

    querygre() {
      console.log(this.queryData);
      selectEnergyStoragePlanScheme(this.queryData).then((res) => {
        if (res.resultCode === 0) {
          // this.dataTree = res.data
          console.log(res.data);
          this.planName = res.data.planName;
          this.energyPlanTarget = res.data.energyPlanTarget;
          this.pconstraint = res.data.pconstraint + "kW";
          this.energyConstraint = res.data.energyConstraint + "kWh";
          this.feederId = res.data.feederId;
          this.countConstraint = res.data.countConstraint + "台";
        }
      });
    },

    // querybuttonTable() {
    //   CLlist(this.queryData).then((res) => {
    //     if (res.resultCode === 0) {
    //       // this.dataTree = res.data
    //     }
    //   })
    // },

    // 给树节点添加唯一标识
    dataTreeFn(data) {
      for (const item of data) {
        if (item.list) {
          item.id = item.name;
          this.dataTreeFn(item.list);
        } else {
          item.id = item.id;
          this.allIds.push(item.id);
        }
      }
    },

    async queryList() {
      list(this.queryDetailParam).then((res) => {
        if (res.resultCode === 0) {
          this.dataTree = res.data;
          console.log(res.data);
        }
      });
    },

    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },

    // 获取渲染树的数据
    // getTreeData(data) {
    //   queryOfExperimentalresults(data).then((res) => {
    //     this.dataTree = addStationName(res.data);
    //     // console.log(data.stationId+"111111");
    //     this.$nextTick(function () {
    //       if (data == undefined) {
    //         this.$refs.equipmentTree.setCheckedKeys([]);
    //         this.checkList = [];
    //         this.queryParamStationId = "";
    //       } else {
    //         this.$refs.equipmentTree.setCheckedKeys([data.stationId], false);
    //         let list = [data.stationId];
    //         this.queryParamStationId = data.stationId;
    //         console.log(list);
    //         this.checkList = list;

    //         let params = {
    //           regulationOrgIds: [],
    //           stationIds: list,
    //           fileSort: "01",
    //         };
    //         this.queryDetailParam = params;
    //         params.stationIds.forEach((e, i) => {
    //           // console.log(params.regulationOrgIds.includes(getAllParentNodes(this.dataTree,e)[0].id))
    //           if (
    //             params.regulationOrgIds.includes(
    //               getAllParentNodes(this.dataTree, e)[0].id
    //             )
    //           ) {
    //             // 找到这个元素删掉他
    //             this.queryDetailParam.stationIds =
    //               this.queryDetailParam.stationIds.filter((d) => d !== e);
    //           }
    //         });
    //         this.$nextTick(() => {
    //           this.$refs.windPowerTable.getDataInit();
    //         });
    //       }
    //     });
    //   });
    // },
    // 下拉框change事件
    inputChange(val) {
      // console.log(val, "搜索下拉框val");
      // console.log(this.$refs.equipmentTree.queryInputListCopy, "搜索下拉框val");
      let param = {
        stationId: val,
      };
      this.getTreeData(param);
    },
    // 点击树的勾选框
    // handleCheck(checkedKeys, e) {
    //   if (this.queryParamStationId !== "") {
    //     console.log("有查询条件");
    //     let params = {
    //       regulationOrgIds: [],
    //       stationIds: [],
    //       fileSort: "01",
    //     };

    //     if (e.checkedKeys[1]) {
    //       params.stationIds.push(e.checkedKeys[1]);
    //     }
    //     this.queryDetailParam = params;
    //   } else {
    //     console.log("无查询条件");
    //     let nodeList = this.$refs.equipmentTree.getCheckedNodes();
    //     let params = {
    //       regulationOrgIds: [],
    //       stationIds: [],
    //       fileSort: "01",
    //     };
    //     nodeList
    //       .filter((e) => e.level !== "3")
    //       .forEach((item) => {
    //         if (item.level === "1") {
    //           params.regulationOrgIds.push(item.id);
    //         }
    //         if (item.level === "2") {
    //           params.stationIds.push(item.id);
    //         }
    //       });
    //     this.queryDetailParam = params;
    //     params.stationIds.forEach((e, i) => {
    //       if (
    //         params.regulationOrgIds.includes(
    //           getAllParentNodes(this.dataTree, e)[0].id
    //         )
    //       ) {
    //         // 找到这个元素删掉他
    //         this.queryDetailParam.stationIds =
    //           this.queryDetailParam.stationIds.filter((d) => d !== e);
    //       }
    //     });
    //   }
    //   this.$nextTick(() => {
    //     this.$refs.windPowerTable.getDataInit();
    //   });
    // },
    // 处理三级节点之间勾选联动
    // checkChange(row, col, check) {
    //   //console.log(this.dataTree, "this.dataTree");
    //   if (row.level == "3") {
    //     // console.log(row, col, check, "row, col");
    //     let checkedKeys = findSiblingIds(this.dataTree, row.id);
    //     // console.log(checkedKeys,'checkedKeyscheckedKeys')
    //     checkedKeys.forEach((item) => {
    //       this.$refs.equipmentTree.setChecked(item.id, col);
    //     });
    //   }
    // },

    handleClear() {
      this.getTreeData();
    },

    // 网架图
    initIframeFn() {
      // 网架图地址
      this.dxtUrl =
        "http://pdyzz.test.com.cn/graph/Navigator.html?graph=新西169线单线图.sln.pic.g";

      // 点位
      let msg = JSON.stringify({
        func: "showImageOnDevices",
        param0: ["2000000471635"],
        param1: "001.png",
        param2: 50,
        param3: 50,
      });

      this.$nextTick(() => {
        document.getElementById("iframe").contentWindow.postMessage(msg, "*");
      });
    },
  },
};
